package com.chen.palmar.project.init;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chen.palmar.R;
import com.chen.palmar.base.BaseFragment;
import com.chen.palmar.common.constant.AppConstant;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.BannerImageLoader;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.common.widget.view.DrawableCenterTextView;
import com.chen.palmar.common.widget.view.SquareImageView;
import com.chen.palmar.entity.HomeBanEntity;
import com.chen.palmar.entity.HomeInfoEntity;
import com.chen.palmar.entity.HomeListEntity;
import com.chen.palmar.project.home.ApplyInfoActivity;
import com.chen.palmar.project.home.ApplyTypeActivity;
import com.chen.palmar.project.home.ImageListActivity;
import com.chen.palmar.project.home.InfoDetailActivity;
import com.chen.palmar.project.home.SearchListActivity;
import com.chen.palmar.project.home.SupplyActivity;
import com.orhanobut.logger.Logger;
import com.primb.androidlibs.net.entity.MessageEvent;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;
import com.sunfusheng.marqueeview.MarqueeView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;

/**
 * @author Chen
 * @date 2017/12/28
 * 功能描述：
 */

public class HomeFragment extends BaseFragment {

    @Bind(R.id.banner_view)
    Banner bannerView;
    @Bind(R.id.et_search)
    DrawableCenterTextView etSearch;
    @Bind(R.id.rv_last_info)
    RecyclerView rvLastInfo;
    @Bind(R.id.swipe_home)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.iv_info_news)
    ImageView ivInfoNews;
    @Bind(R.id.tv_purchase)
    TextView tvPurchase;
    @Bind(R.id.tv_supply)
    TextView tvSupply;
    @Bind(R.id.tv_purchase_content)
    MarqueeView tvPurchaseContent;
    @Bind(R.id.tv_supply_content)
    MarqueeView tvSupplyContent;
    @Bind(R.id.tv_supply_info)
    TextView tvSupplyInfo;
    @Bind(R.id.tv_purchase_info)
    TextView tvPurchaseInfo;
    @Bind(R.id.scroll)
    NestedScrollView scroll;
    @Bind(R.id.ly_home_top)
    LinearLayout lyHomeTop;
    private List<Object> images = new ArrayList<>();
    private List<HomeListEntity.DataBean> dataList = new ArrayList<>();
    private BaseQuickAdapter<HomeListEntity.DataBean, BaseViewHolder> adapter;
    private int page = 0;
    private int pageSize = 10;
    private boolean isLoadComplete = false;
    private ArrayList<String> infoSupply = new ArrayList<>();
    private ArrayList<String> infoPurchase = new ArrayList<>();

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //注册事件
        EventBus.getDefault().register(this);
        initData();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void initData() {
        int statusBarHeight = -1;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            //获取status_bar_height资源的ID
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                //根据资源ID获取响应的尺寸值
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
                Logger.v(statusBarHeight + "---");
                ViewGroup.LayoutParams params = lyHomeTop.getLayoutParams();
                AutoLinearLayout.LayoutParams layoutParams = new AutoLinearLayout.LayoutParams(AutoLinearLayout.LayoutParams.MATCH_PARENT, AutoLinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(30, statusBarHeight + 25, 30, 25);
                lyHomeTop.setLayoutParams(layoutParams);
            }
        }

        etSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), SearchListActivity.class));
            }
        });

        scroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                if (scrollY > oldScrollY) {
                    Logger.v("Scroll DOWN");
                }
                if (scrollY < oldScrollY) {
                    Logger.v("Scroll UP");
                }

                if (scrollY == 0) {
                    Logger.v("TOP SCROLL");
                }

                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    page += 1;
                    getListData(true);
                }
            }
        });

        rvLastInfo.setFocusable(false);

        refreshLayout.setOnRefreshListener(() -> {
            try {
                isLoadComplete = false;
                getDataForWeb();
            } catch (Exception e) {
                e.printStackTrace();
                showToast("服务器数据格式异常");
                refreshLayout.setRefreshing(false);
            }
        });
        refreshLayout.setRefreshing(true);
        refreshLayout.setColorSchemeColors(ContextCompat.getColor(getContext(), android.R.color.holo_blue_bright), ContextCompat.getColor(getContext(), android.R.color.holo_green_light), ContextCompat.getColor(getContext(), android.R.color.holo_orange_light), ContextCompat.getColor(getContext(), android.R.color.holo_red_light));


        //设置指示器位置（当banner模式中有指示器时）
        bannerView.setIndicatorGravity(BannerConfig.CENTER);
        bannerView.setImageLoader(new BannerImageLoader());

        rvLastInfo.setNestedScrollingEnabled(false);
        rvLastInfo.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvLastInfo.setLayoutManager(linearLayoutManager);
        rvLastInfo.setItemAnimator(new DefaultItemAnimator());
        adapter = new BaseQuickAdapter<HomeListEntity.DataBean, BaseViewHolder>(R.layout.item_home, dataList) {
            @Override
            protected void convert(BaseViewHolder helper, HomeListEntity.DataBean item) {
                helper.setText(R.id.tv_item_home_content, item.getContent());
                helper.setText(R.id.tv_item_home_good, item.getPraise_nums() + "");
                helper.setText(R.id.tv_item_home_watch, item.getBrowse_nums() + "");
                helper.setText(R.id.tv_item_home_location, item.getAddress_detail());
                helper.setText(R.id.tv_item_home_name, item.getUser_name());
                helper.setText(R.id.tv_item_date, item.getCreate_at());
                helper.setText(R.id.tv_item_home_type, item.getType() == 1 ? "供应" : "采购");
                helper.setBackgroundRes(R.id.tv_item_home_type, item.getType() == 1 ? R.drawable.shape_supply_bg : R.drawable.shape_purchase_bg);
                helper.setText(R.id.tv_item_home_state, item.getLabelName());

                CircleImageView head = (CircleImageView) helper.getView(R.id.iv_item_home_head);
                Glide.with(getContext()).load(item.getUser_avatar()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).fitCenter().into(head);
                RecyclerView rvImg = (RecyclerView) helper.getView(R.id.rv_item_home_img);
                rvImg.setNestedScrollingEnabled(false);
                rvImg.setHasFixedSize(true);
                GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
                layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                rvImg.setLayoutManager(layoutManager);
                BaseQuickAdapter<String, BaseViewHolder> adapterImg = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_home_img) {
                    @Override
                    protected void convert(BaseViewHolder helper, String item) {
                        SquareImageView view = (SquareImageView) helper.getView(R.id.iv_item_img);
                        Glide.with(getContext()).load(item).override(AppConstant.SCREEN_WIDTH / 3, AppConstant.SCREEN_WIDTH / 3).placeholder(R.mipmap.occupy_icon).error(R.mipmap.occupy_icon).fitCenter().into(view);
                        helper.addOnClickListener(R.id.iv_item_img);
                    }
                };
                adapterImg.setOnItemChildClickListener(new OnItemChildClickListener() {
                    @Override
                    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                        Intent intent = new Intent(getContext(), ImageListActivity.class);
                        intent.putStringArrayListExtra("info", ((ArrayList<String>) item.getImgList()));
                        startActivity(intent);
                    }
                });
                rvImg.setItemAnimator(new DefaultItemAnimator());
                adapterImg.setNewData(item.getImgList());
                rvImg.setAdapter(adapterImg);
            }
        };
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(getContext(), InfoDetailActivity.class);
            intent.putExtra("info", adapter.getData().get(position).getArticleId() + "");
            startActivity(intent);
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getContext(), ImageListActivity.class);
                intent.putStringArrayListExtra("info", ((ArrayList<String>) ((HomeListEntity.DataBean) adapter.getData().get(position)).getImgList()));
                startActivity(intent);
            }
        });
        rvLastInfo.setAdapter(adapter);

        try {
            getDataForWeb();
        } catch (Exception e) {
            e.printStackTrace();
            showToast("服务器数据格式异常");
            refreshLayout.setRefreshing(false);
        }

        bannerView.setOnBannerListener(position -> {
            if (images.size() > 0) {
                HomeBanEntity.DataBean dataBean = (HomeBanEntity.DataBean) images.get(position);
                Intent intent = new Intent(getContext(), InfoDetailActivity.class);
                intent.putExtra("info", dataBean.getRef_id() + "");
                startActivity(intent);
            }
        });

        tvPurchaseContent.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
                if (infoPurchase.size() > 0 && infoPurchase.size() > position) {
                    Intent intent = new Intent();
                    intent.putExtra("info", infoPurchase.get(position));
                    intent.setClass(getContext(), InfoDetailActivity.class);
                    startActivity(intent);
                }
            }
        });

        tvSupplyContent.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
                if (infoSupply.size() > 0 && infoSupply.size() > position) {
                    Intent intent = new Intent();
                    intent.putExtra("info", infoSupply.get(position));
                    intent.setClass(getContext(), InfoDetailActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    private void getDataForWeb() throws Exception {
        getBannerData();
        getInfoData(1);
        getInfoData(2);
        getListData(false);
    }

    /**
     * 轮播图数据
     */
    private void getBannerData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "1");
        map.put("position", "1");
        Subscription banSub = DataCenter.homeBanInfo(map).subscribe(new HttpSubscriber<HomeBanEntity>(getContext(), null) {
            @Override
            public void onNext(HomeBanEntity homeEntity) {
                images.clear();
                images.addAll(homeEntity.getData());
                bannerView.setImages(images);
                bannerView.start();
            }
        });
        subscription.add(banSub);
    }

    /**
     * 信息广场数据
     */
    private void getInfoData(int type) {
        HashMap<String, String> map = new HashMap<>();
        map.put("type", type + "");
        map.put("page", "1");
        map.put("page_size", "1");
        Subscription infoSub = DataCenter.homeInfoInfo(map).subscribe(new HttpSubscriber<HomeInfoEntity>(getContext(), null) {

            @Override
            public void onNext(HomeInfoEntity homeEntity) {
                ArrayList<String> info = new ArrayList<>();
                ArrayList<String> ids = new ArrayList<>();
                for (int i = 0; i < homeEntity.getData().size(); i++) {
                    HomeInfoEntity.DataBean dataBean = homeEntity.getData().get(i);
                    info.add(dataBean.getTitle());
                    ids.add(dataBean.getArticleId() + "");
                }
                if (type == 1) {//供应1，采购2
                    infoSupply.clear();
                    infoSupply.addAll(ids);
                    tvSupplyContent.startWithList(info);
                } else {
                    infoPurchase.clear();
                    infoPurchase.addAll(ids);
                    tvPurchaseContent.startWithList(info);
                }
            }
        });
        subscription.add(infoSub);
    }

    /**
     * 数据动态列表
     */
    private void getListData(boolean isLoad) {
        if (!isLoad) {
            page = 0;
        } else if (isLoadComplete) {
            showToast("数据已全部加载");
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("articleType", "");
        map.put("page", page + "");
        map.put("page_size", pageSize + "");
        Subscription listSub = DataCenter.homeListInfo(map).subscribe(new HttpSubscriber<HomeListEntity>(getContext(), null) {
            @Override
            public void onNext(HomeListEntity homeEntity) {
                if (!isLoad) {
                    dataList.clear();
                    dataList.addAll(homeEntity.getData());
                    adapter.setNewData(dataList);
                    if (dataList.size() < pageSize) {
                        isLoadComplete = true;
                    } else {
                        isLoadComplete = false;
                    }
                } else {
                    dataList.addAll(homeEntity.getData());
                    adapter.notifyDataSetChanged();
                    if (homeEntity.getData().size() < pageSize) {
                        isLoadComplete = true;
                    } else {
                        isLoadComplete = false;
                    }
                }
                refreshLayout.setRefreshing(false);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                refreshLayout.setRefreshing(false);
                if (isLoad) {
                    page -= 1;
                } else {
                    page = 0;
                }
            }
        });
        subscription.add(listSub);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) {
        switch (messageEvent.getEventType()) {
            case ApplyInfoActivity.EVENT_INFO_CODE:
                try {
                    getDataForWeb();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }


    //如果你需要考虑更好的体验，可以这么操作
    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        bannerView.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        bannerView.stopAutoPlay();
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(false);
        }
    }

    @OnClick({R.id.tv_supply_info, R.id.tv_purchase_info, R.id.tv_home_apply})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            //            case R.id.tv_supply_content:
            //                if (TextUtils.isEmpty(tvSupplyContent.getTag().toString())) {
            //                    return;
            //                }
            //                intent.putExtra("info", tvSupplyContent.getTag().toString());
            //                intent.setClass(getContext(), InfoDetailActivity.class);
            //                startActivity(intent);
            //                break;
            //            case R.id.tv_purchase_content:
            //                if (TextUtils.isEmpty(tvPurchaseContent.getTag().toString())) {
            //                    return;
            //                }
            //                intent.putExtra("info", tvPurchaseContent.getTag().toString());
            //                intent.setClass(getContext(), InfoDetailActivity.class);
            //                startActivity(intent);
            //                break;
            case R.id.tv_supply_info:
                intent.setClass(getContext(), SupplyActivity.class);
                intent.putExtra("info", "1");
                startActivity(intent);
                break;
            case R.id.tv_purchase_info:
                intent.putExtra("info", "2");
                intent.setClass(getContext(), SupplyActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_home_apply:
                intent.setClass(getContext(), ApplyTypeActivity.class);
                startActivity(intent);
                break;

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
